package com.lib.image.preview

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.lib.image.R
import com.lib.image.databinding.FragmentCoverListBinding
import com.lib.image.until.HeterotypicScreenUtils
import com.providerlib.fileprovider.FileProvider7
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy

class CoverListFragment : Fragment() {

    companion object {
        private const val REQUEST_CODE = 1001
    }

    private lateinit var mViewModel: CoverViewModel

    private lateinit var mAdapter: CoverAdapter

    private lateinit var mViewBinding: FragmentCoverListBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = ViewModelProvider(requireActivity()).get(CoverViewModel::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mViewBinding = FragmentCoverListBinding.inflate(inflater, container, false)
        return mViewBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mViewBinding.run {
            listItem.layoutManager = GridLayoutManager(requireActivity(), 4)
            val size = HeterotypicScreenUtils.getScreenWidth(requireActivity()) / 4
            mAdapter = CoverAdapter(size)
            mViewModel.getCoverSelection().observe(viewLifecycleOwner, Observer {
                val list = setupEntityList(it)
                mAdapter.data.addAll(list)
                listItem.adapter = mAdapter
            })
            btnBack.setOnClickListener {
                activity?.finish()
            }

            mAdapter.setOnAddClickListener {
                openAlbum()
            }

            mAdapter.setOnReplaceClickListener { item, position ->
                openClip(item.path, position)
            }
        }
    }

    private fun setupEntityList(coverSelection: CoverSelection):List<MultiItemEntity> {
        val list = mutableListOf<MultiItemEntity>()
        coverSelection.pathArray.forEachIndexed { index, s ->
            list.add(CoverDefault(s, index == coverSelection.index))
        }
        list.add(CoverAdd())
        return list
    }

    //重新选择图片
    private fun openAlbum() {
        Matisse.from(this)
            .choose(MimeType.ofImage(), false)
            .countable(true)
            .capture(true)
            .captureStrategy(
                CaptureStrategy(true, FileProvider7.getFileProviderName(requireActivity()), "test")
            )
            .maxSelectable(1)
            .gridExpectedSize(resources.getDimension(R.dimen.preview_select_image).toInt())
            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .thumbnailScale(0.85f)
            .imageEngine(GlideEngine())
            .showSingleMediaType(true)
            .originalEnable(true)
            .maxOriginalSize(10)
            .autoHideToolbarOnSingleTap(true)
            .forResult(REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode != Activity.RESULT_OK) return
        if(requestCode == REQUEST_CODE) {
            //打开新页面
            val list = Matisse.obtainPathResult(data)
            val path = list[0]
            openClip(path, mAdapter.data.size)
        }
    }

    private fun openClip(path: String, index: Int) {
        val bundle = Bundle()
        bundle.putString("path", path)
        bundle.putInt("index", index)
        val args = CoverClipFragmentArgs.Builder(CoverClipFragmentArgs.fromBundle(bundle)).build()
        Navigation.findNavController(requireView()).navigate(R.id.fragment_cover_clip, args.toBundle())
    }
}